/**
 * 基础菜单 库存管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>库存管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input
          size="small"
          v-model="formInline.name"
          placeholder="输入产品名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-input
          size="small"
          v-model="formInline.code"
          placeholder="输入产品编号"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleEdit()"
          >添加</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="downloadFun()"
          >下载</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="inputProduct()"
          >入库</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="outputInventoryFun()"
          >出库</el-button
        >
        <el-upload
          class="upload"
          :multiple="true"
          :limit="1"
          :action="doUpload()"
        >
          <el-button size="small" type="primary" icon="el-icon-plus"
            >点击上传</el-button
          >
        </el-upload>
        <!-- <button @click="playVoiceClick">播放语音</button> -->
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      :data="listData"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      :row-class-name="tableRowClassName"
      style="width: 100%"
    >
      <!-- <el-table-column align="center" type="selection" width="60" >
      </el-table-column> -->

      <el-table-column prop="alarm" label="alarm" v-if="false">
      </el-table-column>
      <el-table-column align="center" prop="name" label="产品名称" width="100">
      </el-table-column>
      <el-table-column align="center" prop="code" label="产品编号" width="100">
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="inventory"
        label="库存"
        width="80"
      >
      </el-table-column>
      <el-table-column align="center" prop="unit" label="单位" width="70">
      </el-table-column>
      <el-table-column
        align="center"
        prop="alarmValue"
        label="告警值"
        width="70"
      >
      </el-table-column>
      <el-table-column
        align="center"
        prop="storeHouse"
        label="库房"
        width="100"
      >
      </el-table-column>
      <el-table-column align="center" prop="site" label="货架" width="100">
      </el-table-column>
      <el-table-column align="center" prop="type" label="型号" width="100">
      </el-table-column>
      <el-table-column align="center" prop="img" label="产品图片" width="70">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.imgPath"
            :preview-src-list="scope.row.imgPaths"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="createTime"
        label="创建时间"
        width="150"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.createTime | timestampToTime }}</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="createUser"
        label="创建人"
        width="70"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="updateTime"
        label="修改时间"
        width="150"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.updateTime | timestampToTime }}</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="updateUser"
        label="修改人"
        width="70"
      >
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button
            size="mini"
            style="background-color: #f5652c; color: white"
            @click="handleSet(scope.$index, scope.row)"
            >设置告警</el-button
          >
          <el-button
            size="mini"
            type="success"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="deleteProduct(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="30%"
      @click="closeDialog"
    >
      <el-form
        label-width="120px"
        :model="editForm"
        :rules="rules"
        ref="editForm"
      >
        <el-form-item label="产品名称" prop="name">
          <el-input
            size="small"
            v-model="editForm.name"
            auto-complete="off"
            placeholder="请输入产品名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="产品编号" prop="code">
          <el-input
            size="small"
            v-model="editForm.code"
            auto-complete="off"
            placeholder="请输入产品编号"
          ></el-input>
        </el-form-item>
        <el-form-item label="库存数量" prop="inventory">
          <el-input
            size="small"
            v-model="editForm.inventory"
            auto-complete="off"
            placeholder="请输入库存数量"
          ></el-input>
        </el-form-item>
        <el-form-item label="库房" prop="storeHouse">
          <el-input
            size="small"
            v-model="editForm.storeHouse"
            auto-complete="off"
            placeholder="请输入库房"
          ></el-input>
        </el-form-item>
        <el-form-item label="位置" prop="site">
          <el-input
            size="small"
            v-model="editForm.site"
            auto-complete="off"
            placeholder="请输入位置"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品型号" prop="type">
          <el-input
            size="small"
            v-model="editForm.type"
            auto-complete="off"
            placeholder="请输入产品型号"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片上传">
          <el-upload
            class="upload-demo"
            drag
            :action="imageUpload(editForm.code)"
            limit="5"
            multiple
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <!-- 入库弹框编辑 -->
    <el-dialog
      :title="title"
      :visible.sync="inputInventory"
      width="45.37%"
      @click="closeInputDialog"
    >
      <el-form
        label-width="120px"
        :model="storageProduct"
        :rules="rules"
        ref="storageProduct"
      >
        <el-form-item label="产品编号" prop="code">
          <el-input
            size="small"
            v-model="storageProduct.code"
            placeholder="输入产品编号"
          ></el-input>
        </el-form-item>

        <div style="text-align: center">
          <el-button
            size="medium"
            type="success"
            @click="fetchBarcode(storageProduct.code)"
            style="center"
            >点击获取条形码</el-button
          >

          <h1>获取后扫描产品条形码</h1>
          <!-- 添加用于显示条形码的 img 标签 -->
          <img
            :src="barCodeImage"
            alt="Barcode"
            v-if="barCodeImage"
            style="width: 450px; height: 100px"
          />
        </div>

        <el-table
          size="small"
          :data="storageProductData"
          highlight-current-row
          v-loading="loading"
          border
          element-loading-text="拼命加载中"
          :row-class-name="tableRowClassName"
          style="width: 100%"
        >
          <el-table-column prop="alarm" label="alarm" v-if="false">
          </el-table-column>
          <el-table-column
            align="center"
            prop="name"
            label="产品名称"
            width="100"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="code"
            label="产品编号"
            width="100"
          >
          </el-table-column>
          <el-table-column
            align="center"
            sortable
            prop="inventory"
            label="库存数量"
            width="100"
          >
          </el-table-column>
          <el-table-column
            align="center"
            sortable
            prop="inventorySum"
            label="入库数量"
            width="100"
          >
            <template slot-scope="scope">
              <el-input
                size="small"
                v-model="scope.row.inventorySum"
                placeholder="入库数量"
                @input="updateInventorySum(scope.$index, scope.row)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="unit" label="单位" width="60">
          </el-table-column>
          <el-table-column
            align="center"
            prop="alarmValue"
            label="告警值"
            width="60"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="storeHouse"
            label="库房"
            width="100"
          >
          </el-table-column>
          <el-table-column align="center" prop="site" label="货架" width="100">
          </el-table-column>
          <el-table-column align="center" prop="type" label="型号" width="100">
          </el-table-column>
        </el-table>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeInputDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="inputInventoryFun('storageProduct')"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <!-- 出库弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="outputInventory"
      width="45.37%"
      @click="closeOutputDialog"
    >
      <el-form
        label-width="120px"
        :model="storageProduct"
        :rules="rules"
        ref="storageProduct"
      >
        <el-form-item label="产品编号" prop="code">
          <el-input
            size="small"
            v-model="storageProduct.code"
            placeholder="输入产品编号"
          ></el-input>
        </el-form-item>

        <div style="text-align: center">
          <el-button
            size="medium"
            type="success"
            @click="fetchBarcode(storageProduct.code)"
            style="center"
            >点击获取条形码</el-button
          >

          <h1>获取后扫描产品条形码</h1>
          <!-- 添加用于显示条形码的 img 标签 -->
          <img
            :src="barCodeImage"
            alt="Barcode"
            v-if="barCodeImage"
            style="width: 450px; height: 100px"
          />
        </div>

        <el-table
          size="small"
          :data="storageProductData"
          highlight-current-row
          v-loading="loading"
          border
          element-loading-text="拼命加载中"
          :row-class-name="tableRowClassName"
          style="width: 100%"
        >
          <el-table-column prop="alarm" label="alarm" v-if="false">
          </el-table-column>
          <el-table-column
            align="center"
            prop="name"
            label="产品名称"
            width="100"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="code"
            label="产品编号"
            width="100"
          >
          </el-table-column>
          <el-table-column
            align="center"
            sortable
            prop="inventory"
            label="库存数量"
            width="100"
          >
          </el-table-column>
          <el-table-column
            align="center"
            sortable
            prop="inventoryRemove"
            label="出库数量"
            width="100"
          >
            <template slot-scope="scope">
              <el-input
                size="small"
                v-model="scope.row.inventoryRemove"
                placeholder="出库数量"
                @input="updateInventorySumRemove(scope.$index, scope.row)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="unit" label="单位" width="60">
          </el-table-column>
          <el-table-column
            align="center"
            prop="alarmValue"
            label="告警值"
            width="60"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="storeHouse"
            label="库房"
            width="100"
          >
          </el-table-column>
          <el-table-column align="center" prop="site" label="货架" width="100">
          </el-table-column>
          <el-table-column align="center" prop="type" label="型号" width="100">
          </el-table-column>
        </el-table>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeOutputDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="outputInventoryFun('storageProduct')"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <!-- 设置告警界面 -->
    <el-dialog
      :title="title"
      :visible.sync="setAlarmVisible"
      width="30%"
      @click="closeAlarmDialog"
    >
      <el-form
        label-width="120px"
        :model="setForm"
        :rules="rules"
        ref="setForm"
      >
        <el-form-item label="产品名称" prop="name">
          <el-input
            size="small"
            v-model="setForm.name"
            auto-complete="off"
            placeholder="请输入产品名称"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="产品编号" prop="code">
          <el-input
            size="small"
            v-model="setForm.code"
            auto-complete="off"
            placeholder="请输入产品编号"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="库存数量" prop="inventory">
          <el-input
            size="small"
            v-model="setForm.inventory"
            auto-complete="off"
            placeholder="请输入库存数量"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="告警数量" prop="alarmValue">
          <el-input
            size="small"
            v-model="setForm.alarmValue"
            auto-complete="off"
            placeholder="请输告警数量"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeAlarmDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitSetAlarmForm('setForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import {
  productList,
  productSave,
  productDelete,
  alarmSave,
  excelUpload,
  excelDownload,
} from "../../api/basisMG";
import Pagination from "../../components/Pagination";
import { playVoice } from "../../api/voice"; // 语言播报
export default {
  data() {
    return {
      title: "出库",
      code: "",
      nextCode: "",
      lastCode: "",
      nextTime: "",
      lastTime: "",
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      setAlarmVisible: false, // 设置告警的显示与隐藏
      inputInventory: false, // 设置入库的显示与隐藏
      outputInventory: false, // 设置出库显示与隐藏
      codeValue: "",
      barCodeImage: "", // 用于存储条形码图片的 Base64 编码字符串
      inventorySumInput: "", // 用于入库数量输入的数据属性
      inventorySumRemove: "", // 用于出库数量输入的数据属性
      storageProductData: "", // 扫码条形码后存储数据
      // 文件上传
      fileList: [
        {
          name: "food.jpeg",
          url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        },
        {
          name: "food2.jpeg",
          url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        },
      ],

      // 编辑保存获取参数
      editForm: {
        id: "",
        name: "",
        code: "",
        inventory: "",
        storeHouse: "",
        site: "",
        type: "",
        imageUrl: "", // 新增图片属性
        token: localStorage.getItem("logintoken"),
      },
      // 设置告警获取参数
      setForm: {
        id: "",
        name: "",
        code: "",
        inventory: "",
        alarmValue: "",
        token: localStorage.getItem("logintoken"),
      },

      // 点击入库/出库获取参数
      storageProduct: {
        name: "",
        code: "",
        inventory: "",
        inventorySum: "",
        inventoryRemove: "",
        unit: "",
        alarmValue: "",
        storeHouse: "",
        site: "",
        type: "",
        location: "",
        token: localStorage.getItem("logintoken"),
      },
      // rules表单验证
      rules: {
        name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入产品编号", trigger: "blur" }],
        inventory: [
          { required: true, message: "请输入库存数量", trigger: "blur" },
        ],
        storeHouse: [
          { required: true, message: "请输入库房", trigger: "blur" },
        ],
        site: [{ required: true, message: "请输入位置", trigger: "blur" }],
        type: [{ required: true, message: "请输入产品型号", trigger: "blur" }],
      },
      // 页面列表显示
      formInline: {
        page: 1,
        limit: 10,
        varLable: "",
        varName: "",
        token: localStorage.getItem("logintoken"),
      },
      // 删除
      seletedata: {
        ids: "",
        token: localStorage.getItem("logintoken"),
      },
      userparm: [], //搜索权限
      listData: [], //库存管理数据
      // listInputProducts: [], // 入库列表数据（扫描条形码后的数据）
      listOutputProducts: [], // 入库列表数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10,
      },
    };
  },
  // 监听页面关闭情况（刷新）
  watch: {
    // 监听 outputInventory 的变化
    outputInventory(newVal) {
      if (!newVal) {
        // 当对话框关闭时（newVal 为 false），刷新页面
        window.location.reload();
      }
    },
    // 监听 inputInventory 的变化
    inputInventory(newVal) {
      if (!newVal) {
        // 当对话框关闭时（newVal 为 false），刷新页面
        window.location.reload();
      }
    },
  },
  // 注册组件
  components: {
    Pagination,
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    this.getdata(this.formInline);
    // this.fetchBarcode();
  },

  mounted() {
    // 在组件挂载后添加键盘事件监听器
    document.addEventListener("keypress", this.handleKeyPress);
  },
  beforeDestroy() {
    // 在组件销毁前移除键盘事件监听器
    document.removeEventListener("keypress", this.handleKeyPress);
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取公司列表
    getdata(parameter) {
      this.loading = true;
      // 模拟数据开始

      // 模拟数据结束

      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      // 查询-页面列表展示
      productList(parameter)
        .then((res) => {
          this.loading = false;
          if (res.success == false) {
            this.$message({
              type: "info",
              message: res.msg,
            });
          } else {
            this.listData = res.data;
            // 分页赋值
            this.pageparm.currentPage = this.formInline.page;
            this.pageparm.pageSize = this.formInline.limit;
            this.pageparm.total = res.count;
          }
        })
        .catch((err) => {
          this.loading = false;
          this.$message.error("菜单加载失败，请稍后再试！");
        });
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage;
      this.formInline.limit = parm.pageSize;
      this.getdata(this.formInline);
    },
    // 搜索事件
    search() {
      this.getdata(this.formInline);
    },

    // 点击入库弹框界面
    inputProduct: function (index, row) {
      this.inputInventory = true;
      this.title = "入库";
      this.storageProduct.name = row.name;
      this.storageProduct.code = row.code;
      this.storageProduct.inventory = row.inventory;
      this.inventorySumInput = row.inventorySum;
      this.storageProduct.unit = row.unit;
      this.storageProduct.alarmValue = row.alarmValue;
      this.storageProduct.storeHouse = row.storeHouse;
      this.storageProduct.site = row.site;
      this.storageProduct.type = row.type;
      this.storageProduct.location = row.location;
    },

    // 点击出库弹框界面
    outputProduct: function (index, row) {
      this.outputInventory = true;
      this.title = "出库";
      this.storageProduct.name = row.name;
      this.storageProduct.code = row.code;
      this.storageProduct.inventory = row.inventory;
      this.inventorySumRemove = row.inventoryRemove;
      this.storageProduct.unit = row.unit;
      this.storageProduct.alarmValue = row.alarmValue;
      this.storageProduct.storeHouse = row.storeHouse;
      this.storageProduct.site = row.site;
      this.storageProduct.type = row.type;
      this.storageProduct.location = row.location;
    },

    // 设置告警
    handleSet: function (index, row) {
      this.setAlarmVisible = true; // 点击设置告警时，显示设置页面
      this.title = "设置告警限制值";
      this.setForm.id = row.id;
      this.setForm.name = row.name;
      this.setForm.code = row.code;
      this.setForm.inventory = row.inventory;
      this.setForm.alarmValue = row.alarmValue;
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        this.title = "修改";
        this.editForm.id = row.id;
        this.editForm.name = row.name;
        this.editForm.code = row.code;
        this.editForm.img = row.img;
        this.editForm.inventory = row.inventory;
        this.editForm.storeHouse = row.storeHouse;
        this.editForm.site = row.site;
        this.editForm.type = row.type;
      } else {
        this.title = "添加";
        this.editForm.id = "";
        this.editForm.name = "";
        this.editForm.code = "";
        this.editForm.inventory = "";
        this.editForm.storeHouse = "";
        this.editForm.site = "";
        this.editForm.type = "";
        this.editForm.img = "";
      }
    },

    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          productSave(this.editForm)
            .then((res) => {
              this.editFormVisible = false;
              this.loading = false;
              if (res.success) {
                this.getdata(this.formInline);
                this.$message({
                  type: "success",
                  message: "产品保存成功！",
                });
              } else {
                this.$message({
                  type: "info",
                  message: res.msg,
                });
              }
            })
            .catch((err) => {
              this.editFormVisible = false;
              this.loading = false;
              this.$message.error("产品保存失败，请稍后再试！");
            });
        } else {
          return false;
        }
      });
    },

    // 设置告警保存界面
    submitSetAlarmForm(editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          alarmSave(this.setForm)
            .then((res) => {
              this.setAlarmVisible = false;
              this.loading = false;
              if (res.success) {
                this.getdata(this.formInline);
                this.$message({
                  type: "success",
                  message: "设置告警成功！",
                });
              } else {
                this.$message({
                  type: "info",
                  message: res.msg,
                });
              }
            })
            .catch((err) => {
              this.setAlarmVisible = false;
              this.loading = false;
              this.$message.error("设置告警失败，请稍后再试！");
            });
        } else {
          return false;
        }
      });
    },
    // 删除产品
    deleteProduct(index, row) {
      this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          productDelete(row.id)
            .then((res) => {
              if (res.success) {
                this.$message({
                  type: "success",
                  message: "产品已删除!",
                });
                this.getdata(this.formInline);
              } else {
                this.$message({
                  type: "info",
                  message: res.msg,
                });
              }
            })
            .catch((err) => {
              this.loading = false;
              this.$message.error("产品删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 文件上传
    doUpload: function () {
      return "api/file/upload?&token=" + localStorage.getItem("logintoken");
    },

    // 文件下载
    downloadFun() {
      excelDownload()
        .then((res) => {
          let url = window.URL.createObjectURL(new Blob([res]), { type: "" });
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", "all_sample_fa_kegg_blast_bst.xls"); //指定下载后的文件名，防跳转
          document.body.appendChild(link);
          link.click();
        })
        .catch((err) => {
          // this.setAlarmVisible = false;
          this.loading = false;
          this.$message.error("文件下载失败，请稍后再试！");
        });
    },

    // 图片上传
    imageUpload(code) {
      return (
        "api/upload/avatar?code=" +
        code +
        "&token=" +
        localStorage.getItem("logintoken")
      );
    },

    // 获取条形码显示
    fetchBarcode(code) {
      if (code == null) {
        this.$message.error("请输入产品编号");
        return;
      }
      // this.title = "入库";
      // this.inputInventory = true; // 如果需要，可以显示加载状态
      const formData = new URLSearchParams();
      formData.append("code", code);
      axios
        .post("/api/Bar/code", formData, {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((response) => {
          if (response.data.msg === "000") {
            this.$message.warning("当前产品库存为0，无法执行出库！");
          }
          if (response.data && response.data.barCodeImage) {
            this.barCodeImage = response.data.barCodeImage; // 设置条形码图片
          } else {
            this.$message.error("获取条形码失败");
          }
        })
        .catch((error) => {
          console.error("获取条形码时发生错误:", error);
          this.$message.error("获取条形码失败");
        });
    },

    // 键盘事件处理函数
    handleKeyPress(e) {
      // 不需要创建 vm 变量，直接使用 this
      if (e.which) {
        // 现代浏览器
        this.storageProduct.nextCode = e.which; // 将 nextCode 属性添加到 formInline 对象上
      }
      if (e.which === 13) {
        // 键盘回车事件
        if (this.storageProduct.code.length > 0) {
          console.log("扫码结束。", this.storageProduct.code);
          this.parseQRCode(this.storageProduct.code); // 调用 parseQRCode 方法处理扫码结果
          this.storageProduct.code = ""; // 清空条形码值，准备下一次扫码
          this.storageProduct.lastCode = ""; // 将 lastCode 也放在 storageProduct 对象上
          this.storageProduct.lastTime = ""; // 将 lastTime 也放在 storageProduct 对象上
        }
        return;
      }

      this.storageProduct.nextTime = new Date().getTime(); // 将 nextTime 属性添加到 storageProduct 对象上
      if (!this.storageProduct.lastTime && !this.storageProduct.lastCode) {
        this.storageProduct.code = e.key; // 开始扫码，记录第一个字符
      } else {
        this.storageProduct.code += e.key; // 继续扫码，追加字符
      }

      this.storageProduct.lastCode = this.storageProduct.nextCode; // 更新 lastCode
      this.storageProduct.lastTime = this.storageProduct.nextTime; // 更新 lastTime
    },

    // 扫描条形码，获取后端数据
    parseQRCode(code) {
      if (code.length === 0) {
        console.log("请输入条码！");
      } else {
        // 发送请求到后端获取产品信息
        axios
          .post("/api/getProductByCode", { code: code })
          .then((res) => {
            if (res.data && res.data.success) {
              console.log("获取产品信息成功：", res.data.data);
              // 根据需求更新 Vue 实例的数据属性
              this.storageProductData = res.data.data;
              console.log(this.storageProduct);
            } else {
              this.$message.error("获取产品信息失败");
            }
          })
          .catch((error) => {
            console.error("获取产品信息时发生错误:", error);
            this.$message.error("获取产品信息失败");
          });
      }
      // 注意：这里不需要再设置 this.codeValue = code，除非您在模板中使用了它
    },

    // 判断入库输入是否正确
    updateInventorySum(index, value) {
      // 将输入的值转换为数字
      const numValue = Number(value);
      // 验证输入的值是否是整数
      if (Number.isInteger(numValue)) {
        // 使用 Vue 的 $set 方法来确保响应式更新
        this.$set(this.storageProductData, index, {
          ...this.storageProductData[index],
          inventorySum: numValue,
        });
      } else {
        // 如果输入的不是整数，可以选择性地给用户反馈
        console.error("请输入有效的整数");
      }
    },

    // 判断出库输入是否正确
    updateInventorySumRemove(index, value) {
      // 将输入的值转换为数字
      const numValue = Number(value);
      // 验证输入的值是否是整数
      if (Number.isInteger(numValue)) {
        // 使用 Vue 的 $set 方法来确保响应式更新
        this.$set(this.storageProductData, index, {
          ...this.storageProductData[index],
          inventoryRemove: numValue,
        });
      } else {
        // 如果输入的不是整数，可以选择性地给用户反馈
        console.error("请输入有效的整数");
      }
    },

    // 入库
    inputInventoryFun() {
      this.inputInventory = true;
      this.loading = true; // 开始加载

      // 确保 inventorySum 已被更新
      const updatedDataInput = this.storageProductData.map((row) => ({
        ...row,
        inventorySum: row.inventorySum, // 直接使用已经更新过的值
      }));

      // 获取token
      const token = localStorage.getItem("logintoken");

      // 发送数据到后端
      axios
        .post("/api/saveInventory", updatedDataInput, {
          headers: {
            Authorization: `Bearer ${token}`, // 假设使用的是 Bearer token
          },
        })
        .then((res) => {
          if (res.data.success) {
            // 处理成功响应
            console.log("入库成功", res.data.data);

            // 尝试播放音频
            playVoice("入库成功！");

            // 可以考虑刷新页面或显示成功消息
            this.$message.success("入库成功");

            // 使用 setTimeout 在一秒后刷新页面
            setTimeout(() => {
              window.location.reload(); // 刷新页面   this.$router.go(0); 重新加载当前路由，相当于刷新页面
            }, 300); // 1000 毫秒等于 1 秒
          }
        })
        .catch((error) => {
          // 处理错误响应
          console.error("入库失败", error);
          playVoice("入库失败！");
          // 显示错误信息
          this.$message.error("入库失败，请稍后再试");
        })
        .finally(() => {
          this.inputInventory = false; // 关闭对话框
          this.loading = false; // 结束加载
        });
    },

    // 出库
    outputInventoryFun() {
      this.outputInventory = true;
      this.loading = true; // 开始加载

      // 获取token
      const token = localStorage.getItem("logintoken");

      // 发送数据到后端
      axios
        .post("/api/removeInventory", this.storageProductData, {
          headers: {
            Authorization: `Bearer ${token}`, // 假设使用的是 Bearer token
          },
        })
        .then((res) => {
          if (res.data.success) {
            // 尝试播放音频
            playVoice("出库成功！");

            // 处理成功响应
            console.log("出库成功", res.data.data);
            // 可以考虑刷新页面或显示成功消息
            this.$message.success("出库成功");

            // 使用 setTimeout 在一秒后刷新页面
            setTimeout(() => {
              window.location.reload(); // 刷新页面   this.$router.go(0); 重新加载当前路由，相当于刷新页面
            }, 300); // 1000 毫秒等于 1 秒
          } else {
            this.$message.error(res.data.data);
          }
        })
        .catch((error) => {
          // 处理错误响应
          console.error("出库失败", error);
          playVoice("出库失败！");
          // 显示错误信息
          this.$message.error(res.data.data);
        })
        .finally(() => {
          this.loading = false; // 结束加载
        });
    },

    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false;
    },

    // 关闭告警弹框
    closeAlarmDialog() {
      this.setAlarmVisible = false; // 关闭设置告警界面
    },

    // 关闭入库弹框
    closeInputDialog() {
      this.inputInventory = false;
      this.$router.go(0); // 关闭弹框时，清除前端缓存
    },

    // 关闭出库弹框
    closeOutputDialog() {
      this.outputInventory = false;
      this.$router.go(0); // 关闭弹框时，清除前端缓存
    },

    // 库存不足发生告警提示
    tableRowClassName(row, rowIndex) {
      if (row.row.alarm == 0) {
        return "";
      }
      return "warning-row"; // 设置告警显示（高亮）
    },

    // 测试语音播报功能
    // playVoiceClick(){
    //   playVoice("入库成功！");
    // }
  },
};
</script>

<!-- <style scoped> --> 
<style >
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}

.el-table .success-row {
  background: #f5652c;
}
.el-table .warning-row {
  background: #ff9c22d4;
}
</style>

 
 